<?php

namespace app\admin\controller;

use app\admin\validate\CompanyOrderValidate;
use app\service\traits\Crud;
use app\admin\model\CompanyOrder as CompanyOrderModel;
use app\admin\model\CompanyUser;

class CompanyOrder extends Base
{
    private CompanyOrderModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new CompanyOrderModel();
        $this->validateClass = CompanyOrderValidate::class;
        $this->withSearch    = 'status,id,company_id,create_time,no,order_status';
        $this->append        = 'order_status_text';
        $this->hidden        = 'type,pay_type,voucher,delete_time';
    }


    public function format($list): mixed
    {
        return $list->each(function ($item) {
            $item->goods_type_count = $item->companyOrderDetails()->count();//商品种类
            $item->goods_count      = $item->companyOrderDetails()->sum('quantity');//商品总数
            $item->goods_amount     = $item->companyOrderDetails()->sum('amount');//商品总价
            $item->company_name     = $item->company()->value('name');//公司名称
            $item->company_user     = CompanyUser::where('company_id', $item->company_id)->admin()->field('real_name,mobile')->find();
        });
    }

    public function detailFormat($info): mixed
    {
        $field              = 'id,goods_id,goods_rule_id,quantity,money,amount,purchasing_price';
        $info->details      = $info->companyOrderDetails()->field($field)->select()->each(function ($item) {
            $item->goods        = $item->goods()->withTrashed()->value('name');
            $item->goods_rule   = $item->goodsRule()->withTrashed()->field('spec_name,img')->find();
        });
        $info->company      = $info->company()->withTrashed()->field('name,address')->find();//公司名称,地址
        $info->company_user = CompanyUser::where('company_id', $info->company_id)->withTrashed()->admin()->field('real_name,mobile')->find();
        $info->order_log    = $info->companyOrderLogs()->select();
        return $info->hidden(explode(',', $this->hidden));
    }

}